package com.gillion.grule.client.components;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gillion.grule.client.core.Component;
import com.gillion.grule.client.core.Context;
import com.gillion.grule.client.core.ExecuteComponent;
import com.gillion.grule.client.executor.DroolsRuleExecutor;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

import org.mvel2.MVEL;
import org.springframework.beans.factory.annotation.Autowired;





@Component("Rule")
public class RuleComponent extends ExecuteComponent
{
    @Autowired
    private DroolsRuleExecutor droolsRuleExecutor;

    private ObjectMapper objectMapper = new ObjectMapper();

    public <T> T execute(String express, Context context) {


        Map<String, Object> expressMap = JSON.parseObject(express, new TypeReference<Map<String, Object>>() {});

        String groupId = MapUtils.getString(expressMap, "groupId");
        String artifactId = MapUtils.getString(expressMap, "artifactId");

        List<String> params = (List<String>)expressMap.get("params");
        if (CollectionUtils.isEmpty(params)) {
            return (T)this.droolsRuleExecutor.execute(groupId, artifactId, new Object[0]);
        }

        List<Object> args = Lists.newArrayList();
        for (String param : params) {
            Object o = MVEL.eval(param, context);
            args.add(o);
        }
        return (T)this.droolsRuleExecutor.execute(groupId, artifactId, args.toArray());
    }
    public <T> T execute(String groupId, String artifactId, Object... args) {
        return (T)this.droolsRuleExecutor.execute(groupId, artifactId, args);
    }



}